from ChartReport.Template import RenderContext
import jinja2
from jinja2 import utils as jinja_utils
import types


def hack_jinja_template_render(jinja_template: jinja2.Template, ctx: RenderContext):

    def hack_context_resolve(obj):
        org_func = obj.resolve_or_missing

        def change_context_resolve(self, key):
            print(f'change_context_resolve:{key}')
            value = org_func(key)

            return

        obj.resolve_or_missing = types.MethodType(change_context_resolve, obj)

    def change_render(self, *args, **kwargs):
        vars = dict(*args, **kwargs)
        try:
            ctx = self.new_context(vars)
            hack_context_resolve(ctx)
            return jinja_utils.concat(self.root_render_func(ctx))
        except Exception:
            self.environment.handle_exception()

    jinja_template.render = types.MethodType(change_render, jinja_template)
